package com.fable.common.config;

import com.fable.base.ComponentException;
import com.fable.common.enums.BusiErrCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static com.fable.common.utils.ConvertErrorCodeUtil.*;

public class ExceptionResolver implements HandlerExceptionResolver {

    private static final Logger LOG = LoggerFactory.getLogger(ExceptionResolver.class);

    private static final String REDIRECT_ERROR = "redirect:/error.htm";

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView mv = new ModelAndView();

        // json请求
        String requestURI=request.getRequestURI();
        if (StringUtils.isNoneBlank(requestURI)&&requestURI.endsWith(".json")) {
            mv.setView(createJsonView(ex,requestURI));
            return mv;
        }

        // 非json请求
        mv.addObject(ERROR_MESSAGE, dealErrorMessage(ex,requestURI));
        mv.setViewName(REDIRECT_ERROR);
        return mv;
    }

    private MappingJackson2JsonView createJsonView(Exception ex,String requestURI) {
        MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
        jsonView.addStaticAttribute(SUCCESS, false);
        jsonView.addStaticAttribute(ERROR_MESSAGE, dealErrorMessage(ex,requestURI));
        return jsonView;
    }

    private String dealErrorMessage(Exception ex,String requestURI) {
        String msg = BusiErrCode.SERVER_BUSY.msg();
        if (ex instanceof ComponentException) {
            msg = getErrorMessage(((ComponentException) ex).getErrCode());
        }
        LOG.error("error in ExceptionResolver ex:" + ex);
        LOG.error("error in ExceptionResolver msg:" + msg);
        LOG.error("error requestURI:"+requestURI);
        return msg;
    }
}
